﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Future.Web.Filter
{
    /// <summary>
    /// 正常结果格式化返回
    /// </summary>
    public class SucceededUnifyResultFilter : IAsyncActionFilter
    {
        /// <summary>
        /// action执行后格式化结果
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 执行 Action 并获取结果
            ActionExecutedContext actionExecutedContext = await next();

            IActionResult result = default!;

            // 判断是请求结果存在异常，不进行处理
            if (actionExecutedContext.Exception != null) return;

            if (actionExecutedContext.Result is not null && CheckVaildResult(actionExecutedContext.Result, out var data))
            {
                if (data is not null)
                {
                    result = new OkObjectResult(ResultVo.Success(data, "操作成功"));
                }
            }

            // 如果是不能规范化的结果类型，则跳过
            if (result == null) return;

            actionExecutedContext.Result = result;
        }

        /// <summary>
        ///  检查是否是有效的结果（可进行格式化）
        /// </summary>
        /// <param name="result"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private static bool CheckVaildResult(IActionResult result, out object? data)
        {
            data = new object();

            // 排除以下结果，跳过规范化处理
            bool isDataResult = result switch
            {
                ViewResult => false,
                PartialViewResult => false,
                FileResult => false,
                ChallengeResult => false,
                SignInResult => false,
                SignOutResult => false,
                RedirectToPageResult => false,
                RedirectToRouteResult => false,
                RedirectResult => false,
                RedirectToActionResult => false,
                LocalRedirectResult => false,
                ForbidResult => false,
                ViewComponentResult => false,
                PageResult => false,
                ContentResult => false,
                _ => true,
            };

            // 目前支持返回值 ActionResult
            if (isDataResult)
            {
                data = result switch
                {
                    // 处理对象结果
                    ObjectResult obj => obj.Value,
                    // 处理 JSON 对象
                    JsonResult json => json.Value,
                    _ => new object(),
                };
            }

            return isDataResult;
        }
    }
}
